<template>
  <div class="query" v-loading="loading">
    <div class="checks" v-show="isShow">
      <h3>{{ $t("选择字段") }}</h3>
      <el-checkbox
        v-for="option in fields"
        :key="option.Name"
        v-model="option.checked"
        :label="$t(option.Desc)"
        size="large"
        @change="checkChanged"
        border
      />
      <div style="margin-top: 20px">
        <h4>{{ $t("数据频率") }}</h4>
        <el-radio-group v-model="freq" @change="freqChanged">
          <el-radio border :label="5">5{{ $t("秒") }}</el-radio>
          <el-radio border :label="30">30{{ $t("秒") }}</el-radio>
          <el-radio border :label="60">1{{ $t("分钟") }}</el-radio>
          <el-radio border :label="1">1{{ $t("秒") }}</el-radio>
        </el-radio-group>
      </div>
    </div>
    <h3>{{ $t("时间查询") }}</h3>
    <el-form :model="timeQuery" inline>
      <el-form-item :label="$t('起始时间')">
        <el-date-picker
          v-model="timeQuery.startTime"
          type="datetime"
          :picker-options="startPickerOptions"
          style="width: 200px"
          :format="
            state.lang === 'en' ? 'DD/MM/YYYY HH:mm:ss' : 'YYYY-MM-DD HH:mm:ss'
          "
        ></el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('结束时间')">
        <el-date-picker
          v-model="timeQuery.endTime"
          type="datetime"
          :picker-options="endPickerOptions"
          style="width: 200px"
          :format="
            state.lang === 'en' ? 'DD/MM/YYYY HH:mm:ss' : 'YYYY-MM-DD HH:mm:ss'
          "
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchByTime">{{
          $t("查询")
        }}</el-button>
      </el-form-item>
    </el-form>

    <el-table
      class="my-table"
      ref="singleTableRef"
      :data="tableData"
      style="width: 100%"
      highlight-current-row
      @row-click="rowClick"
      @filter-change="search_filter"
    >
      <el-table-column prop="bm_BatchNo" :label="$t('批号')"></el-table-column>
      <el-table-column
        prop="RecordTime"
        :label="$t('时间')"
        :formatter="timeFormatter"
      ></el-table-column>

      <el-table-column
        prop="step_rcp_run_step_rcp_type"
        column-key="step_rcp_run_step_rcp_type"
        :label="$t('工艺')"
        :formatter="typeFormatter"
        :filters="[
          { text: '[]', value: '0' },
          { text: 'PBMC', value: '1' },
          { text: 'SPIN', value: '2' },
          { text: 'BEADWASH', value: '3' },
          { text: 'DILUTION', value: '4' },
          { text: 'CULTUREWASH', value: '5' },
        ]"
        :filter-method="filterType"
      ></el-table-column>
      <el-table-column
        prop="bm_LastUser"
        :label="$t('用户')"
        column-key="bm_LastUser"
        :filters="typeFilters_User"
        :filter-method="filterType_User"
      ></el-table-column>
    </el-table>

    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      :page-size="pageSize"
      @current-change="handleCurrentChange"
      style="margin-top: 20px"
    >
    </el-pagination>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance,
  computed,
  watch,
} from "vue";
import {
  ElTable,
  ElTableColumn,
  ElInput,
  ElButton,
  ElPagination,
  ElMessageBox,
} from "element-plus";
import { state } from "../router";
import router from "../router";
import * as utils from "../utils/utils";
import moment from "moment";

const instance = getCurrentInstance();
const $axios = instance.proxy.$axios;
const $message = instance.proxy.$message;
const $t = instance.proxy.$t;

const fields = ref([]);
const isShow = ref(0);
const loading = ref(true);

const freq = ref(30);
const step_rcp_type = ref("0,1,2,3,4,5");
const typeFilters_User = ref([]); //所有的用户
const bm_LastUser_Filter = ref([]); //选择的用户

const timeQuery = reactive({
  startTime: "",
  endTime: "",
});

const singleTableRef = ref(null);
const tableData = ref([]);
const total = ref(0);
const currentRow_Batch = ref(0);
const currentRow_RcpType = ref(0);
const currentPage = ref(1);
const pageSize = ref(calculatePageSize());

function calculatePageSize() {
  if (window.location.href.indexOf("query/curve") != -1) {
    // 历史曲线
    return 9;
  } else {
    return 3; //表格
  }
}

//http://localhost:3000/curve/his?
//?start_time=2023-03-14+08:56:15&end_time=2023-03-14+10:56:15
//&table_name=Data1&db=local&fields=f1,f2,f8&lang=zh&freq=3
const startPickerOptions = computed(() => ({
  disabledDate(time) {
    const oneMonthAgo = new Date();
    oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
    return true;
    //   time.getTime() < oneMonthAgo.getTime() || time.getTime() > Date.now()
  },
}));

const endPickerOptions = computed(() => ({
  disabledDate(time) {
    return true;
    // return time.getTime() < Date.now();
  },
}));
const timeSpan = computed(() => {
  if (timeQuery.startTime && timeQuery.endTime) {
    const startTime = new Date(timeQuery.startTime).getTime();
    const endTime = new Date(timeQuery.endTime).getTime();
    return endTime - startTime;
  }
  return 0;
});
function validateDates() {
  if (timeQuery.startTime >= timeQuery.endTime) {
    ElMessageBox.alert($t("开始时间必须小于结束时间"), $t("提示"), {
      confirmButtonText: $t("确认"),
    });
    return false;
  }
  var hour = (timeSpan.value / (1000 * 60 * 60 * 24)).toFixed(2);
  if (hour > 48) {
    ElMessageBox.alert($t("时间跨度不能超过") + hour + $t("小时"), $t("提示"), {
      confirmButtonText: $t("确认"),
    });
    return false;
  }
  return true;
}
const searchByTime = () => {
  console.log(timeQuery.startTime, timeQuery.endTime, currentRow_Batch.value);
  if (validateDates() == false) {
    return;
  }
  if (!utils.compareTimeRange(timeQuery.startTime, timeQuery.endTime)) {
    console.log("时间查询范围不得超过10个小时");
    ElMessageBox.alert($t("时间查询范围不得超过10个小时"), $t("提示"), {
      confirmButtonText: $t("确认"),
    });
    return;
  }
  let hasTime2 = timeQuery.startTime != "" && timeQuery.endTime != "";
  let hasTime1 = timeQuery.startTime != null && timeQuery.endTime != null;
  let hasTime = hasTime1 && hasTime2;
  if (!hasTime && currentRow_Batch.value == "") {
    ElMessageBox.alert($t("请选择时间或批号"), $t("提示"), {
      confirmButtonText: $t("确认"),
    });
    return;
  }

  let query = {
    ...state,
    ...state.query,
    freq: freq.value,
  };

  if (timeQuery.startTime != "" && timeQuery.endTime != "") {
    // 这里始终使用 YYYY-MM-DD HH:mm:ss 格式
    let start_time = moment(timeQuery.startTime).format("YYYY-MM-DD HH:mm:ss");
    let end_time = moment(timeQuery.endTime).format("YYYY-MM-DD HH:mm:ss");
    query = {
      ...query,
      start_time,
      end_time,
    };
  }
  if (currentRow_Batch.value != "") {
    query["batch"] = currentRow_Batch.value;
    query["rcp_type"] = currentRow_RcpType.value;
  }
  if (state.params.query_name == "curve") {
    delete query.last; //后台收到如果有last属性,会优先处理last最新的数据,忽略开始和结束时间,因为这里是查询页面,也就必定有时间范围,所以删除last数据
    router.push({
      path: `/curve/his`, // 使用路由地址传递参数
      query,
    });
  } else if (state.params.query_name == "table") {
    query["fields"] = getCheckedFields();
    router.push({
      path: `/table`, // 使用路由地址传递参数
      query,
    });
  } else {
    location.reload();
    // ElMessageBox.alert(`未找到query_name${state.params.query_name}`, "提示", {
    //   confirmButtonText: $t("确认"),
    // });
  }
};
function getCheckedFields() {
  const checkedFields = fields.value
    .filter((item) => item.checked === true)
    .map((item) => item.Name); //Name是数据库字段名
  return checkedFields;
}
const rowClick = async (val) => {
  try {
    if (currentRow_Batch.value == val.bm_BatchNo) {
      currentRow_Batch.value = "";
      currentRow_RcpType.value = "";
      singleTableRef.value.setCurrentRow();
    } else {
      singleTableRef.value.setCurrentRow(val);
      currentRow_Batch.value = val.bm_BatchNo;
      currentRow_RcpType.value = val.step_rcp_run_step_rcp_type;

      const { data } = await $axios.get("/get_time_range", {
        params: {
          db: state.db,
          table_name: `Data${state.tbid}`,
          batch: val.bm_BatchNo,
        },
        timeout: 5000,
      });

      // 后端始终返回 YYYY-MM-DD HH:mm:ss 格式，所以这里固定使用这个格式解析
      const s = moment(data.start_time, "YYYY-MM-DD HH:mm:ss").toDate();
      const e = moment(data.end_time, "YYYY-MM-DD HH:mm:ss").toDate();
      timeQuery.startTime = s;
      timeQuery.endTime = e;
    }
  } catch (error) {
    console.error("获取时间范围失败:", error);
    $message.error($t("网络连接失败，请检查网络后重试"));
    currentRow_Batch.value = "";
    currentRow_RcpType.value = "";
    singleTableRef.value.setCurrentRow();
    timeQuery.startTime = "";
    timeQuery.endTime = "";
  }
};

const timeFormatter = (row, column, cellValue) => {
  if (!cellValue) return "";
  return state.lang === "en"
    ? moment(cellValue).format("DD/MM/YYYY HH:mm:ss")
    : moment(cellValue).format("YYYY-MM-DD HH:mm:ss");
};

const search = async () => {
  loading.value = true;
  try {
    //比较数组
    function arraysEqual(arr1, arr2) {
      if (arr1.length !== arr2.length) {
        return false;
      }
      for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) {
          return false;
        }
      }
      return true;
    }
    // 将 state.groups 和 state.accounts 从字符串转换为数组
    const groupsArray = state.groups.map((group) => group.toLowerCase()); //不区分大小写
    const accountsArray = state.accounts;

    let use_not_in = 0; // 默认值 不使用NOT IN 的数据库查询语法
    // 检查是否包含特定的组，不区分大小写
    const containsSpecialGroup =
      groupsArray.includes("manufacture") ||
      groupsArray.includes("administrators");
    // 检查 bm_LastUser_Filter.value 和 accountsArray 是否相等
    if (
      containsSpecialGroup &&
      arraysEqual(bm_LastUser_Filter.value, accountsArray)
    ) {
      use_not_in = 1;
    }

    const { data } = await $axios.get("/batch-no-list", {
      params: {
        page_number: currentPage.value,
        page_size: pageSize.value,
        db: state.db,
        tbid: state.tbid,
        step_rcp_type: step_rcp_type.value,
        accounts: bm_LastUser_Filter.value.join(","),
        use_not_in: use_not_in, // 新增参数
      },
    });
    tableData.value = data.data;
    total.value = data.total_items;
    loading.value = false;
  } catch (error) {
    console.error(error);
    loading.value = false;
  }
};

const search_filter = async (filters) => {
  //   console.log(filters);

  // 处理工艺类型筛选
  if (filters.step_rcp_run_step_rcp_type) {
    step_rcp_type.value = filters.step_rcp_run_step_rcp_type.join(",");
    if (step_rcp_type.value === "") {
      step_rcp_type.value = "0,1,2,3,4,5";
    }
  }

  // 处理用户筛选
  if (filters.bm_LastUser && filters.bm_LastUser.length > 0) {
    // 如果有选中的用户，则更新为选中的用户
    bm_LastUser_Filter.value = filters.bm_LastUser;
  } else {
    // 如果没有选中的用户，则设置为所有用户
    // 这里假设 state.accounts 包含所有用户
    bm_LastUser_Filter.value = state.accounts;
  }

  // 重新搜索
  search();
};

const update_account_list = async () => {
  let result = [];
  for (let d of state.accounts) {
    result.push({
      text: d,
      value: d,
    });
  }
  typeFilters_User.value = result;
  bm_LastUser_Filter.value = state.accounts;
  return; //下面暂时不用，用户通过url传参过来进行过滤
  //   let { data } = await $axios.get("/account-list");
  //   let result = [];
  //   for (let d of data) {
  //     result.push({
  //       text: d,
  //       value: d,
  //     });
  //   }
  //   typeFilters_User.value = result;
};
const getFields = async () => {
  function compareArrays(array1, array2) {
    if (array1.length !== array2.length) {
      return false;
    }
    for (let i = 0; i < array1.length; i++) {
      const obj1 = array1[i];
      const obj2 = array2.find((obj) => obj.Desc === obj1.Desc);
      if (!obj2) {
        return false;
      }
    }
    return true;
  }
  try {
    const { data } = await $axios.get("/table/fields", {
      params: {
        db: state.db,
        tbid: state.tbid,
      },
    });
    let _ = localStorage.getItem(
      `${state.params.query_name}_${state.lang}_fields`
    );
    if (_ != undefined && _ != "") {
      let localAry = JSON.parse(_);

      if (compareArrays(data, localAry)) {
        let index = 0;
        data.forEach((d) => {
          if (localAry[index]["checked"] != undefined) {
            d["checked"] = localAry[index]["checked"];
          }
          index += 1;
        });
      } else {
        localStorage.removeItem(
          `${state.params.query_name}_${state.lang}_fields`
        );
      }
    }
    fields.value = data;
    checkChanged();
  } catch (error) {
    console.error(error);
  }
};

onMounted(() => {
  let _ = localStorage.getItem(`${state.params.query_name}_${state.lang}_freq`);
  if (_ != undefined && _ != "") {
    freq.value = parseInt(_);
  }
  isShow.value = state.params.query_name == "table";

  // 开发环境模拟数据
  if (process.env.NODE_ENV === 'development') {
    tableData.value = generateMockData();
    total.value = pageSize.value * 2; // 假设总数据量是当前页面的2倍
    loading.value = false;
  } else {
    getFields();
    update_account_list();
    search();
  }
});

function generateMockData(count = pageSize.value) {
  const mockData = [];
  const types = ['0', '1', '2', '3', '4', '5'];
  const users = ['user1', 'user2', 'user3', 'admin'];
  
  for (let i = 1; i <= count; i++) {
    const randomType = types[Math.floor(Math.random() * types.length)];
    const randomUser = users[Math.floor(Math.random() * users.length)];
    const randomDate = new Date(Date.now() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000));
    
    mockData.push({
      bm_BatchNo: `BATCH-${1000 + i}`,
      RecordTime: randomDate.toISOString(),
      step_rcp_run_step_rcp_type: randomType,
      bm_LastUser: randomUser
    });
  }
  return mockData;
}

const filterType = (value, row) => {
  console.log(row.step_rcp_run_step_rcp_type, value);
  return row.step_rcp_run_step_rcp_type == value;
};

const filterType_User = (value, row) => {
  console.log(row.bm_LastUser, value);
  return row.bm_LastUser == value;
};
const typeFormatter = (row, column, cellValue) => {
  // 这是一个映射表的例子，你可以根据你的需求进行修改
  const typeMap = {
    0: "[]",
    1: "PBMC",
    2: "SPIN",
    3: "BEADWASH",
    4: "DILUTION",
    5: "CULTUREWASH",
    // 更多的映射...
  };
  return typeMap[cellValue] || cellValue;
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  search();
};
const freqChanged = () => {
  if (state.params.query_name != undefined) {
    localStorage.setItem(
      `${state.params.query_name}_${state.lang}_freq`,
      freq.value.toString()
    );
  }
};

const checkChanged = () => {
  if (state.params.query_name != undefined) {
    localStorage.setItem(
      `${state.params.query_name}_${state.lang}_fields`,
      JSON.stringify(fields.value)
    );
  }
};
</script>

<style scoped>
/* 样式代码 */
.query {
  padding-left: 20px;
  padding-right: 20px;
}

body,
html {
  height: 100%;
  overflow: hidden;
}

.query {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.my-table {
  flex: 1; 
  overflow: auto;
}
/* .my-table::-webkit-scrollbar {
  width: 30px !important;
  height: 30px !important;
} */
</style>
